package cn.cubix.flow.controller.userprms;

import cn.cubix.flow.entity.WfPrms;
import cn.cubix.flow.service.WfPrmsService;
import cn.cubix.flow.util.Result;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@RestController
@RequestMapping("/api/userprms/prms")
@RequiredArgsConstructor(onConstructor=@__({@Autowired,@Lazy}))
public class WfPrmsApi {

    private final WfPrmsService wfPrmsService;

    /** 分页查询系统权限 */
    @PostMapping("/page")
    @PreAuthorize("hasAnyAuthority('ADMIN','API_USERPRMS_PRMS_PAGE')")
    public Object page(@RequestBody JSONObject body){
        long current = 1L, size = 10L, total = 0L;
        if(body.containsKey("page")){
            JSONObject page = body.getJSONObject("page");
            current = page.getLong("current",current);
            size = page.getLong("size",size);
        }
        IPage<WfPrms> page = wfPrmsService.page(new Page<>(current,size));
        return Result.SUCCESS(page.getRecords(),"查询成功").setPage(current,size,page.getTotal());
    }

    /** 新建系统权限 */
    @PostMapping("/create")
    @PreAuthorize("hasAnyAuthority('ADMIN','API_USERPRMS_PRMS_CREATE')")
    public Object create(@RequestBody JSONObject body){
        Result<Object> result = Result.FAILURE().setMessage("保存失败");
        if(body.containsKey("record")){
            JSONObject record = body.getJSONObject("record");
            WfPrms wfPrms = record.toBean(WfPrms.class);
            boolean saveResult = wfPrmsService.save(wfPrms);
            if(saveResult){
                result.toSuccess().setMessage("保存成功");
            }
        }
        return result;
    }

    /** 删除系统权限 */
    @PostMapping("/delete")
    @PreAuthorize("hasAnyAuthority('ADMIN','API_USERPRMS_PRMS_DELETE')")
    public Object delete(@RequestBody JSONObject body){
        Result<Object> result = Result.FAILURE().setMessage("删除失败");
        if(body.containsKey("params")){
            JSONObject params = body.getJSONObject("params");
            Collection<String> ids = Stream.of(params.getStr("id","null").split(",")).collect(Collectors.toList());
            boolean removeResult = wfPrmsService.removeByIds(ids);
            if(removeResult){
                result.toSuccess().setMessage("删除成功");
            }
        }
        return result;
    }

}
